//
//  MainHomePageViewController.m
//  ERP
//
//  Created by QA on 16/4/5.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MainHomePageViewController.h"
#import "GETableView.h"

#import "NSDictionary+DataFormat.h"
#import "TOWebViewController.h"
#import "RTSpinKitView.h"
#import "HYBLoopScrollView.h"

#import "WebViewController.h"
#import "GEPushViewControllerHelper.h"

#import "DateTimeFormat.h"
#import "ModuleAuthorityEntity+CoreDataClass.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MessageInfoService.h"
#import "PlatformServer.h"

#import "MainHomeSCKBHomeViewCell.h"
#import "MainHomeTableViewCell.h"
#import "MainHomeContractManageCell.h"
#import "MainHomeHeaderViewCell.h"
#import "MainHomeOrderViewCell.h"
#import "UINavigationBar+Awesome.h"
#import "UIImage+Color.h"

@interface MainHomePageViewController ()

@property (nonatomic,strong) IBOutlet GETableView *tableView;

@property (nonatomic, strong) NSArray *moduleArray;
@property (nonatomic, strong) NSMutableArray *menuArray;

@end

@implementation MainHomePageViewController

- (id)init
{
    self = [super init];
    if (self) {
        //添加菜单权限获取注册
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMenuAuthorityService:)
                                                     name:GetUserBasicInfoServiceKey object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMenuAuthorityService:)
                                                     name:MessageInfoServiceKey object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMenuAuthorityService:)
                                                     name:PlatformADServiceKey object:nil];
    }
    return self;
}

- (void)dealloc
{
    //移除菜单权限获取注册
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.navigationController.navigationBar lt_reset];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.tableView.contentInset = UIEdgeInsetsMake(-1, 0, 0, 0);
    
    //添加进度条
    RTSpinKitView *spinner = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStyleFadingCircleAlt];
    spinner.center = CGPointMake(SuperWidth / 2, CGRectGetMidY(self.tableView.frame));
    [spinner startAnimating];
    [self.tableView addSubview:spinner];
    
    //获取广告数据
    [[PlatformServer sharedService] startQueryADService];
    
    //获取数据
    [self getSqliteData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor whiteColor]];
    
    //去除黑色阴影线
    UIImage *image = [UIImage imageWithColor:[UIColor colorWithWhite:0.9 alpha:1] size:CGSizeMake(SuperWidth, 0.5)];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6){
        [self.navigationController.navigationBar setShadowImage:image];
    }
    
    //状态栏字体改变
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColorDispose colorWithHexString:@"#333333"], NSForegroundColorAttributeName,
                                                                     [UIFont systemFontOfSize:18.0], NSFontAttributeName, nil]];
}

#pragma mark -
#pragma mark - NSNotificationCenter

-(void)updateMenuAuthorityService:(NSNotification *)notification
{
    //获取菜单权限列表
    if ([[notification name] isEqualToString:GetUserBasicInfoServiceKey]){
        [self getSqliteData];
        
    } else if ([[notification name] isEqualToString:MessageInfoServiceKey]){
        NSString *keyValue = [NSString stringWithFormat:@"oa-office-message"];
        [self.tableView removeSaveCellKey:keyValue];
        [self.tableView reloadData];
        
    } else if ([[notification name] isEqualToString:PlatformADServiceKey]){
        //保存广告数据
        NSString *keyValue = [NSString stringWithFormat:@"oa-system-ad"];
        [self.tableView removeSaveCellKey:keyValue];
        [self.tableView reloadData];
    }
    
}

#pragma mark  获取页面功能权限

- (void)getSqliteData
{
    //获取主模块
    NSPredicate *predicateMain = [NSPredicate predicateWithFormat:@"parentId = %@ and moduleType = %@", @0, @1];
    ModuleAuthorityEntity *mainEntity = [ModuleAuthorityEntity MR_findFirstWithPredicate:predicateMain sortedBy:@"order" ascending:YES];
    
    //获取主菜单
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parentId = %@ and moduleType = %@", mainEntity.id, @1];
    NSArray *moduleArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:predicate];
    self.moduleArray = moduleArray;
    
    //获取菜单功能模块
    self.menuArray = [NSMutableArray array];
    for (ModuleAuthorityEntity *entity in moduleArray) {
        NSPredicate *menuPredicat = [NSPredicate predicateWithFormat:@"parentId = %@ and moduleType = %@", entity.id, @1];
        NSArray *menuArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:menuPredicat];
        [self.menuArray addObject:menuArray];
    }
    
    //页面数据配置
    [self.tableView removeAllSaveCell];
    [self.tableView reloadData];
    
    //移除进度条
    if(self.moduleArray.count <= 0) return;
    NSArray *viewArray = self.tableView.subviews;
    for (id view in viewArray) {
        if ([view isKindOfClass:[RTSpinKitView class]]) {
            RTSpinKitView *mSpinKitView = view;
            [mSpinKitView removeFromSuperview];
        }
    }
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.000001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == 0) return 0.000001f;//广告控件下方不需要分割空间
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
    CGFloat height = [self tableView:tableView heightForRowAtIndexPath:indexPath];
    if(height >= 1) return 10;
    else return 0.000001f;//未找到控件
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //默认会显示广告控件
    return self.moduleArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*****广告控件*****/
    if(indexPath.section == 0){
        NSString *keyValue = [NSString stringWithFormat:@"oa-system-ad"];
        UITableViewCell *cell = [self.tableView getCellViewKey:keyValue];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            //设置广告图片
            NSArray *array = [PlatformServer sharedService].adInfoArray;
            NSMutableArray *imageUrl = [NSMutableArray array];
            for (NSDictionary *entity in array){
                NSString *urlString = [entity objectFormatStringForKey:@"icon"];
                [imageUrl addObject:urlString];
            }
            
            if (imageUrl.count <= 0)
                [imageUrl addObject:[UIImage imageNamed:@"ad_default_img"]];
            
            CGRect frame = CGRectMake(0, 0, SuperWidth, 160);
            if(SuperWidth == 320) frame = CGRectMake(0, 0, SuperWidth, 140);
            
            __weak __typeof(self) weakSelf = self;
            __strong __typeof(NSArray*) weakSelfArray = array;
            HYBLoopScrollView *loopScrollView = [HYBLoopScrollView loopScrollViewWithFrame:frame imageUrls:imageUrl timeInterval:8 didSelect:^(NSInteger atIndex) {
                //数据判断与处理
                if(weakSelfArray.count <= 0) return;
                NSDictionary *entity = [weakSelfArray objectAtIndex:atIndex];
                
                //提交广告统计
                NSString *adID = [entity objectFormatStringForKey:@"id"];
                [[PlatformServer sharedService] updateADVisitsID:adID];
                
                //打开页面方式 0无操作 1网页 2电话
                NSInteger openType = [entity objectFormatIntegerForKey:@"openType"];
                if(openType == 1){
                    //跳转网页模式页面
                    WebPushParameterModel *model = [[WebPushParameterModel alloc] init];
                    model.URL = [entity objectFormatStringForKey:@"webCode"];
                    model.Title = [entity objectFormatStringForKey:@"title"];
                    model.CodeType = CodeTypeWeb;
                    
                    WebViewController *viewController = [[WebViewController alloc] initWithPushParameterModel:model];
                    [weakSelf.navigationController pushViewController:viewController animated:YES];
                    
                } else if(openType == 2){
                    //拨打电话
                    NSString *title = [entity objectFormatStringForKey:@"title"];
                    NSString *webCode = [entity objectFormatStringForKey:@"webCode"];
                    NSArray *arrayPhone = [webCode componentsSeparatedByString:@","];
                    
                    //创建拨打电话提示框
                    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                    for(NSString *phoneNumber in arrayPhone){
                        UIAlertAction *useCamera = [UIAlertAction actionWithTitle:phoneNumber style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            [self callAction:phoneNumber];
                        }];
                        [alertController addAction:useCamera];
                    }
                    //创建取消按钮
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    [alertController addAction:cancelAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                }
                
            } didScroll:nil];
            
            loopScrollView.alignment = kPageControlAlignRight;
            loopScrollView.placeholder = [UIImage imageNamed:@"ad_default_img"];
            loopScrollView.alpha = 0.9f;
            loopScrollView.imageContentMode = UIViewContentModeScaleToFill;
            [cell.contentView addSubview:loopScrollView];
            
            [self.tableView setCellView:cell key:keyValue];
        }
        return cell;
    }
    
    /******************************************************************************************************/
    
    NSArray *array = [self.menuArray objectAtIndex:indexPath.section-1];
    ModuleAuthorityEntity *entity = [self.moduleArray objectAtIndex:indexPath.section-1];
    
    /*****生产管理*****/
    if(entity.module.integerValue == 7){
        //NSString *keyValue = [NSString stringWithFormat:@"ad-%ld-%ld",indexPath.section,indexPath.row];
        NSString *keyValue = [NSString stringWithFormat:@"production_management"];
        MainHomeTableViewCell *cell = [self.tableView getCellViewKey:keyValue];
        if (!cell) {
            cell = [[MainHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
            [cell setMenuArray:array navigation:self.navigationController];
            [self.tableView setCellView:cell key:keyValue];
        }
        return cell;
    }
    
    /*****移动办公*****/
    if(entity.module.integerValue == 2){
        //NSString *keyValue = [NSString stringWithFormat:@"ad-%ld-%ld",indexPath.section,indexPath.row];
        NSString *keyValue = [NSString stringWithFormat:@"oa-office-message"];
        MainHomeTableViewCell *cell = [self.tableView getCellViewKey:keyValue];
        if (!cell) {
            cell = [[MainHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
            [cell setMenuArray:array navigation:self.navigationController];
            [self.tableView setCellView:cell key:keyValue];
        }
        return cell;
    }
    
    /*****其他*****/
    if(entity.module.integerValue == 3){
        NSString *keyValue = [NSString stringWithFormat:@"qt-%ld-%ld",indexPath.section,indexPath.row];
        MainHomeTableViewCell *cell = [self.tableView getCellViewKey:keyValue];
        if (!cell) {
            cell = [[MainHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
            [cell setMenuArray:array navigation:self.navigationController];
            [self.tableView setCellView:cell key:keyValue];
        }
        return cell;
    }
    
    /*****生产监测*****/
    if(entity.module.integerValue == 5){
        NSString *keyValue = [NSString stringWithFormat:@"dz-%ld-%ld",indexPath.section,indexPath.row];
        MainHomeSCKBHomeViewCell *cell = [self.tableView getCellViewKey:keyValue];
        if (!cell) {
            cell = [[MainHomeSCKBHomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.backgroundColor = [UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setNavigation:self.navigationController];
            [self.tableView setCellView:cell key:keyValue];
        }
        return cell;
    }
    
    /*****订单管理*****/
    if(entity.module.integerValue == 6){
        NSString *keyValue = [NSString stringWithFormat:@"MainHomeOrderViewCell-%ld-%ld",indexPath.section,indexPath.row];
        MainHomeOrderViewCell *cell = [self.tableView getCellViewKey:keyValue];
        if (!cell) {
            cell = [[MainHomeOrderViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.backgroundColor = [UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setMenuArray:array navigation:self.navigationController];
            [self.tableView setCellView:cell key:keyValue];
        }
        return cell;
    }
    
    //无数据页面
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //广告控件
    if(indexPath.section == 0){
        if(SuperWidth == 320) return 140;
        else return 160;
    }
    
    ModuleAuthorityEntity *entity = [self.moduleArray objectAtIndex:indexPath.section-1];
    
    //生产管理
    if (entity.module.integerValue == 7){
        if(SuperWidth == 320) return 86;
        else return 93;
    }
    
    //移动办公
    if (entity.module.integerValue == 2){
        if(SuperWidth == 320) return 86;
        else return 93;
    }
    
    //其他
    if (entity.module.integerValue == 3){
        if(SuperWidth == 320) return 93;
        else return 86;
    }
    
    //生产监测
    if (entity.module.integerValue == 5){
        return 100;
    }
    
    //订单管理
    if (entity.module.integerValue == 6){
        return 75;
    }
    
    return 0.00001f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 拨打电话
- (void)callAction:(NSString*)phoneNumber
{
    if (!(phoneNumber && ![phoneNumber isEqualToString:@""])) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未找到联系电话" delegate:self
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    } else {
        phoneNumber = [NSString stringWithFormat:@"tel://%@",phoneNumber];
    }
    
    //拨打电话(合法拨打电话方式)
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:phoneNumber];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

@end
